import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/checkin/checkinmodel.dart';
import 'package:opene/ui/cms/checkin/cmscheckinemptyscreen.dart';
import 'package:opene/ui/cms/cmsmodel.dart';
import 'package:opene/ui/returns/returnsdialogscreen.dart';
import 'package:opene/utils/ImageUtils.dart';
import 'package:toast/toast.dart';

class CMSCheckinScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CMSCheckinScreenPage();
  }
}

class CMSCheckinScreenPage extends StatefulWidget {
  @override
  _CMSCheckinScreenPageState createState() => _CMSCheckinScreenPageState();
}

class _CMSCheckinScreenPageState extends BaseState<CMSCheckinScreenPage> {
  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();

  int index = 0, position;

  PhotoBean bolPhoto = new PhotoBean();
  List<CMSCheckin> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Checkin";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setType();
  }
  void setType() {
    setState(() {
      switch(type){
        case 1:
          textEditingController.text = "";
          bolPhoto = new PhotoBean();
          baseLayoutBottomContent = true;
          next="Submit";
          break;
        case 2:
          setLayoutBottomContentGone();
          data.clear();
          getTallyContainerNo();
          break;
      }

    });
  }

  Future pickImages(context) async {
    if (Utils.isEmpty(textEditingController.text)) {
      ToastContext().init(context);
      Toast.show("There is no container number at present", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    File image = await ImageUtils.chosePhotoOnAlbumOrCamera(context: context);
    print(image.path);
    String name = "";
    bolPhoto.image = image;
    name = "bol";
    setState(() {
      fileUpload(textEditingController.text, "cmscheckin", image, name, index, position, false, false);
      print("index:${index},position:${position}");
      print(image.path);
    });
  }
  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                flex: 1, //设置权重
                child: GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    if (type == 1) {
                      return;
                    }
                    type = 1;
                    setType();

                  },
                  child: Container(
                    padding: EdgeInsets.all(5),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.only(topLeft: Radius.circular(8.0), bottomLeft: Radius.circular(8.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'Pending',
                      style: type == 1 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    if (type == 2) {
                      return;
                    }
                    type = 2;
                    setType();
                  },
                  child: Container(
                    padding: EdgeInsets.all(5),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.only(topRight: Radius.circular(8.0), bottomRight: Radius.circular(8.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'Empty',
                      style: type == 2 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                ),
              ),
            ],
          ),
          Visibility(
            visible: type == 1 ? true : false,
            child: Container(
              margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
              width: double.infinity,
              child: ConstrainedBox(
                constraints: BoxConstraints(maxHeight: 35),
                child: TextField(
                  controller: textEditingController,
                  textInputAction: TextInputAction.search,
                  onSubmitted: (String text) {
                    print('Searching for $text');
                  },
                  // autofocus: true,
                  decoration: InputDecoration(
                    suffixIcon: IconButton(
                      icon: Icon(
                        Icons.qr_code_scanner,
                        size: 20,
                        color: MyAppTheme.nearlyBlue,
                      ),
                      onPressed: () {
                        // requestPermissions();
                        // Utils.scanBarcode(context);
                        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                          return ScanCode();
                        })).then((text) {
                          if (text == null) {
                            return;
                          }
                          print(text); //拿到扫描结果
                        });
                      },
                    ),
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: MyAppTheme.nearlyBlue,
                      ),
                      borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                      // 设置焦点之外的边框颜色
                      borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                      // 设置焦点时的边框颜色
                      borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                    ),
                    hintText: "Select Container Number OR  BOL",
                    filled: true,
                    fillColor: MyAppTheme.white,
                    //隐藏下划线
                    //border: InputBorder.none,
                    hintStyle: TextStyle(color: Colors.grey),
                    contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                  ),
                  onChanged: (text) {
                    code = text;
                  },
                ),
              ),
            ),
          ),
          Visibility(
            visible: type == 1 ? true : false,
            child: setPhotoView("BOL:  ", 0, bolPhoto),
          ),
          SizedBox(height: 5,),
          Visibility(
            visible: type == 2 ? true : false,
            child: Expanded(
              child: setListView(),
            ),
          ),
        ],
      ),
    );
  }

  Container setPhotoView(String hintText, int type, PhotoBean photoBean) {
    return Container(
      height: 70,
      margin: const EdgeInsets.only(left: 0, top: 10, right: 0, bottom: 0),
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Expanded(
            flex: 1, //设置权重
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  '*',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                ),
                Text(
                  hintText,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                ),
              ],
            ),
          ),
          Expanded(
              flex: 2, //设置权重
              child: Row(
                children: [
                  Container(
                    width: 70,
                    height: 70,
                    child: Stack(
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            // 请求焦点
                            FocusScope.of(context).requestFocus(FocusNode());
                            index = type;
                            ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? pickImages(context) : imgFileDialog(photoBean, Constants.baseImgUrl);
                          },
                          child: photoBean.image == null
                              ? (photoBean.urlImg == null
                              ? Image.asset(
                            'assets/images/add.png',
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          )
                              : Image.network(
                            Constants.baseImgUrl + photoBean.urlImg,
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          ))
                              : Image.file(
                            photoBean.image,
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          ),
                        ),
                        Visibility(
                          visible: ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? false : true,
                          child: Positioned(
                            top: 2.0,
                            right: 2.0,
                            child: GestureDetector(
                              onTap: () {
                                setState(() {
                                  photoBean.urlImg = null;
                                  photoBean.image = null;
                                });
                              },
                              child: Image.asset(
                                'assets/images/ic_delete_menu.png',
                                width: 15,
                                height: 15,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    flex: 2, //设置权重
                    child: Text(
                      '',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                    ),
                  ),
                ],
              )),
        ],
      ),
    );
  }
  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        CMSCheckin tally = data[index];
        return Column(
          children: [
            GestureDetector(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => CMSCheckinEmptyScreen(checkinInfo: tally)),
                ).then((value) => {
                  if (value != null && value) {getTallyContainerNo()}
                });
              },
              child:  Row(
                children: [
                  Expanded(
                    flex: 2, //设置权重
                    child: Text(
                      Utils.getStringisEmpty(tally.containerNo),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                    ),
                  ),
                  Icon(Icons.keyboard_arrow_right,size: 20,)
                ],
              ),
            ),

            Divider(),
          ],
        );
      },
    );
  }

  @override
  void setNext() {
    ToastContext().init(context);
    if (Utils.isEmpty(textEditingController.text)) {
      Toast.show("There is no container number at present", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (bolPhoto.image == null) {
      Toast.show("Please add bol photos", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (Utils.isEmpty(bolPhoto.urlImg)) {
      fileUpload(textEditingController.text, "cmscheckin", bolPhoto.image, "bol", 0, position, true, true);
      return;
    }
    UnloadQr unloadQr = new UnloadQr();
    unloadQr.containerNo = textEditingController.text;
    unloadQr.doPho = bolPhoto.urlImg;
    checkSubmit(unloadQr);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      bolPhoto = new PhotoBean();
    });
  }

  void getTallyContainerNo() async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.fbaTransNotifyUnloadPendingContainers);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        data = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => CMSCheckin.fromJson(userJson)).toList());
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    bolPhoto.urlImg = path;
  }

  void checkSubmit(UnloadQr unloadQr) async {
    String json = jsonEncode(unloadQr);
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.fbaTransNotifyUnloadSubmit, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      showDialog(
        context: context,
        builder: (context) => PreprocessSucceedDialog(),
      ).then((value) => {Navigator.of(context).pop(true)});
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
}
